﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace System.Web.UI
{
    /// <summary>
    /// 页面基类。
    /// </summary>
    public class BasePage : Page
    {
        /// <summary>
        /// 页面初始化时让页面立即过期，防止页面缓存。
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.Response.Expires = -1;
        }

        #region 导出当前页列表到Excel
        /// <summary>
        /// 获取或设置当前页面的GridView控件。
        /// </summary>
        protected GridView CurrentGridView
        {
            get;
            set;
        }

        /// <summary>
        /// 导出事件。
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void Export(object source, EventArgs e)
        {
            this.FindGridView(this.Page);
            this.ExportGridView(this.CurrentGridView);
        }

        /// <summary>
        /// 导出指定的GridView,可在派生类中重写。
        /// </summary>
        /// <param name="grid"></param>
        protected virtual void ExportGridView(GridView grid)
        {
            if (grid != null)
            {
                grid.SaveAsXls(string.Format("{0}{1:yyyyMMdd}.xls", this.Page.Title, DateTime.Now), true, false, true);
            }
        }
        
        /// <summary>
        /// 查找指定容器下的GridView控件。
        /// </summary>
        /// <param name="control"></param>
        private void FindGridView(Control control)
        {
            if (control is GridView)
            {
                this.CurrentGridView = control as GridView;
            }
            else
            {
                foreach (Control ctrl in control.Controls)
                {
                    if (ctrl is GridView)
                    {
                        this.CurrentGridView = ctrl as GridView;
                    }
                    if (this.CurrentGridView == null)
                    {
                        FindGridView(ctrl);
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        #endregion
    }
}
